{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "4afcb8f2",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n"
     ]
    }
   ],
   "source": [
    "class Gate:\n",
    "    def __init__(self, gate_type):\n",
    "        self.type = gate_type\n",
    "        self.inputs = []\n",
    "\n",
    "    def compute(self):\n",
    "        if self.type == 'AND':\n",
    "            return all(self.inputs)\n",
    "        elif self.type == 'OR':\n",
    "            return any(self.inputs)\n",
    "        elif self.type == 'NOT':\n",
    "            return not self.inputs[0]\n",
    "\n",
    "class BooleanCircuit:\n",
    "    def __init__(self):\n",
    "        self.gates = []\n",
    "        self.output_gate = None\n",
    "\n",
    "    def add_gate(self, gate):\n",
    "        self.gates.append(gate)\n",
    "\n",
    "    def set_output(self, gate):\n",
    "        self.output_gate = gate\n",
    "\n",
    "    def evaluate(self, inputs):\n",
    "        for gate in self.gates:\n",
    "            gate.inputs = [inputs[i] if isinstance(i, int) else i.compute() for i in gate.inputs]\n",
    "        return self.output_gate.compute()\n",
    "\n",
    "# 示例：构建 (NOT (x1 AND x2)) AND ((x2 AND x3) OR (NOT x3)) 的电路\n",
    "circuit = BooleanCircuit()\n",
    "and0 = Gate('AND')\n",
    "and1 = Gate('AND')\n",
    "and2 = Gate('AND')\n",
    "not0 = Gate('NOT')\n",
    "not1 = Gate('NOT')\n",
    "or0 = Gate('OR')\n",
    "\n",
    "and0.inputs = [0, 1]  # x1 AND x2\n",
    "and1.inputs = [1, 2]     # NOT x3\n",
    "not0.inputs = [2]\n",
    "not1.inputs = [and0]\n",
    "or0.inputs = [and1, not0]\n",
    "and2.inputs = [not1, or0]\n",
    "\n",
    "circuit.add_gate(and0)\n",
    "circuit.add_gate(and1)\n",
    "circuit.add_gate(not0)\n",
    "circuit.add_gate(not1)\n",
    "circuit.add_gate(or0)\n",
    "circuit.add_gate(and2)\n",
    "\n",
    "circuit.set_output(and2)\n",
    "\n",
    "# 评估电路\n",
    "print(circuit.evaluate([False, True, False]))  \n",
    "\n",
    "# 输出: \n",
    "# True\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1f2a8476",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
